import request from './utils/request';
import { SnowflakeId } from './utils/snowflake';

// 生成请求 ID
const snowflake = new SnowflakeId(); // 创建一个单例

function generateRequestId(): string {
    return snowflake.generate();
}

// 定义请求响应类型
export interface ApiResponseData<T> {
    code: number
    data: T
    message: string
}

/**
 * GET 请求
 * @param url - 请求地址
 */
export async function get<T = any>(url: string): Promise<ApiResponseData<T>> {
    const requestId = generateRequestId();
    const separator = url.includes('?') ? '&' : '?';
    const finalUrl = `${url}${separator}requestId=${requestId}`;
    return request.get(finalUrl);
}

/**
 * POST Json 请求
 * @param url - 请求地址
 * @param data - Json数据
 */
export async function postJson<T = any>(url: string, data: { [key: string]: any } | undefined): Promise<ApiResponseData<T>> {
    const requestId = generateRequestId();
    const finalUrl = `${url}?requestId=${requestId}`;
    const config = {
        headers: {
            'Content-Type': 'application/json'
        }
    };
    return request.post(finalUrl, data, config);
}

/**
 * POST Form 请求
 * @param url - 请求地址
 * @param data - 表单数据
 */
export async function postForm<T = any>(url: string, data: Record<string, any>): Promise<ApiResponseData<T>> {
    const formData = new FormData();
    formData.append('requestId', generateRequestId());

    Object.entries(data).forEach(([key, value]) => {
        if (value !== undefined) {
            // 处理 File 类型
            if (value instanceof File) {
                formData.append(key, value);
            }
            // 处理数组
            else if (Array.isArray(value)) {
                value.forEach((item, index) => {
                    formData.append(`${key}[${index}]`, item);
                });
            }
            // 处理对象
            else if (typeof value === 'object' && value !== null) {
                formData.append(key, JSON.stringify(value));
            }
            // 处理基本类型
            else {
                formData.append(key, String(value));
            }
        }
    });
    const config = {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    };
    return request.post(url, formData, config);
}

/**
 * 文件上传
 * @param url - 上传地址
 * @param file - 文件
 * @param onProgress - 上传进度回调
 */
export async function upload<T = any>(
    url: string,
    file: File,
    onProgress?: (progress: number) => void
): Promise<ApiResponseData<T>> {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('requestId', generateRequestId());

    return request.post(url, formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: (progressEvent) => {
            if (onProgress && progressEvent.total) {
                const progress = (progressEvent.loaded * 100) / progressEvent.total;
                onProgress(Math.round(progress));
            }
        }
    });
}